package com.lfy.websocket.handler;


import cn.hutool.extra.spring.SpringUtil;
import com.lfy.modules.common.config.sys.DictionariesKey;
import com.lfy.modules.common.config.sys.SysDictionaries;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import io.netty.handler.codec.http.*;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.Map;
import java.util.stream.Stream;
@Slf4j
public class HttpHeadersHandler extends ChannelInboundHandlerAdapter  {


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        if (!(msg instanceof FullHttpRequest)) {
            ctx.fireChannelRead(msg);

        }
        assert msg instanceof FullHttpRequest;
        FullHttpRequest req = (FullHttpRequest) msg;
        String origin = req.headers().get(HttpHeaderNames.ORIGIN);
        log.info("origin: {}", origin);
        if (origin != null && isAllowedOrigin(origin)) {
            ctx.pipeline().remove(this);
            ctx.fireChannelRead(msg);
        } else {
            // 不允许的Origin，拒绝连接
            ctx.channel().close();
        }

    }
    private boolean isAllowedOrigin(String origin) {
        String or = SysDictionaries.getValue(DictionariesKey.SYS_WEB_SOCKET_URL);
        String allowedOrigin = "https://blog.lvfeiy.top:8090";
        String allowedOrigin2 = "https://blog.lvfeiy.top";
        String allowedOrigin3 = "http://blog.lvfeiy.top:8090";
        String allowedOrigin4 = "http://blog.lvfeiy.top";
        String web4 = "http://127.0.0.1:5173";
        String web6 = "http://127.0.0.1:5174";
        String web7 = "http://localhost:5174";
        String web5 = "http://localhost:5173";
        return Arrays.asList(allowedOrigin,allowedOrigin2,allowedOrigin3,allowedOrigin4, web4, web5,web6,web7,or).contains(origin);

    }





}